package cn.lanqiao.system.controller;

import cn.lanqiao.system.entity.User;
import cn.lanqiao.system.service.UserService;
import cn.lanqiao.system.util.RedisUtilObject;
import cn.lanqiao.system.util.Result;
import cn.lanqiao.system.vo.InsertOrUpdateUserVo;
import cn.lanqiao.system.vo.QueryUserVo;
import cn.lanqiao.system.vo.UserVo;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import static cn.lanqiao.system.util.Result.*;

import java.util.Date;
import java.util.List;

//@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    /**
     * 在yaml配置文件中读取秘钥
     */
    @Value("${cn.lanqiao.key}")
    private String key;

    // /user/check
    @PostMapping("/login")
    public Result checkUser(@RequestBody User user) {
        User retUser = userService.checkUser(user); // user_name 验证
        if (retUser == null) {
            return Result.fail(201, "该用户不存在！");
        } else {
            if (BCrypt.checkpw(user.getPassword(), retUser.getPassword())) {
                //创建token
                String token = JWT.create()
                        .withClaim("userId", retUser.getUserId())//jwt中存用户id
                        .withClaim("userName", retUser.getUserName())//jwt中存用户名
                        .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60))//设置失效时间一小时
                        .sign(Algorithm.HMAC256(key));//设置秘钥。
                return success(token);
            } else {
                return Result.fail(202, "密码错误！");
            }
        }
    }

    @PostMapping("/list")
    public Result getUserListByPage(@RequestBody QueryUserVo userVo) {
        PageHelper.startPage(userVo.getCurrentPage(), userVo.getPageSize());
        List<UserVo> userList = userService.getUserListByPage(userVo);
        PageInfo<UserVo> pageInfo = new PageInfo<>(userList);
        return success(pageInfo);
    }

    @PostMapping("/insert")
    public Result insertUser(@RequestBody InsertOrUpdateUserVo user) {
        //数据处理 : 系统时间  加密password
        user.setCreateTime(new Date());
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        userService.insertUser(user);
        return success();
    }

    @PostMapping("/delete")
    public Result insertUser(@RequestBody User user) {
        userService.deleteUser(user.getUserId());
        return success();
    }
}
